package com.apps.ubc.cc;


import java.util.Calendar;
import java.util.TimeZone;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;




import com.apps.datastore.NoSignupDatastore;
import com.apps.outgoing.EmailNotifier;
import com.apps.services.UBCSectionDetailService;
import com.apps.utils.SMSUtils;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.QueryResultIterator;


public class NoSignUpCheckServlet extends HttpServlet{
	
	private static final String EMAIL_NOTIFICATION = "Course Information Update: <DEPARTMENT> <COURSE> <SECTION> has <NUMBER_OF_SEATS> general seat(s) remaining on <TIMESTAMP>. Please visit this link to register(requires CWL authentication): https://courses.students.ubc.ca/cs/main?pname=subjarea&tname=subjareas&req=5&dept=<DEPARTMENT>&course=<COURSE>&section=<SECTION>";
	private static final String SMS_NOTIFICATION = "Course Information Update: <DEPARTMENT> <COURSE> <SECTION> has <NUMBER_OF_SEATS> general seat(s) remaining on <TIMESTAMP>.";
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp) {

			QueryResultIterator<Entity> i = NoSignupDatastore.getAll();
			while(i.hasNext()){
				Entity e = i.next();
	
					String email = (String) e.getProperty(NoSignupDatastore.EMAIL_PROPERTY);
					String phone = (String) e.getProperty(NoSignupDatastore.PHONE_NUMBER_PROPERTY);
					String dept = (String) e.getProperty(NoSignupDatastore.DEPT_PROPERTY);
					String course = (String) e.getProperty(NoSignupDatastore.COURSE_PROPERTY);
					String section = (String) e.getProperty(NoSignupDatastore.SECTION_PROPERTY);
					
				if((Boolean)e.getProperty(NoSignupDatastore.ACTIVATED_PROPERTY)){
					UBCSectionDetailService details = new UBCSectionDetailService();
					details.init(dept, course, section);
					if(details.getGenSeatsRemain() > 0) {
						String email_str = EMAIL_NOTIFICATION.replaceAll("<DEPARTMENT>", dept).replaceAll("<COURSE>", course).replaceAll("<SECTION>", section).replaceAll("<NUMBER_OF_SEATS>", ""+details.getGenSeatsRemain()).replaceAll("<TIMESTAMP>", Calendar.getInstance(TimeZone.getTimeZone("PST")).getTime().toString());
						String phone_str = SMS_NOTIFICATION.replaceAll("<DEPARTMENT>", dept).replaceAll("<COURSE>", course).replaceAll("<SECTION>", section).replaceAll("<NUMBER_OF_SEATS>", ""+details.getGenSeatsRemain()).replaceAll("<TIMESTAMP>", Calendar.getInstance(TimeZone.getTimeZone("PST")).getTime().toString());
						EmailNotifier.sendMessage(email, email_str);
						SMSUtils.sendSMS(phone, phone_str);
						NoSignupDatastore.deleteNotifier(email, phone, dept, course, section);
					}
				}
				else {
					NoSignupDatastore.deleteNotifier(email, phone, dept, course, section);
				}
			}

	}
	


}
 